<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>表单</title>

    <link rel="stylesheet" href="../lib/css/style.css">
    <link rel="stylesheet" href="../ins/ueditor.css">

    <script src="../../../static/vendor/jquery/jquery.js"></script>
    <script src="../../../static/htmljs/utils.js"></script>

    <style>
        .needs-discussion:not(.djs-connection) .djs-visual > :nth-child(1) {
            stroke: rgba(66, 180, 21, 0.7) !important; /* color elements as red */
        }

        .diagram-note {
            background-color: rgba(66, 180, 21, 0.7);
            color: White;
            border-radius: 5px;
            font-family: Arial;
            font-size: 12px;
            padding: 5px;
            min-height: 16px;
            width: 50px;
            text-align: center;
        }

        #canvas {
            width: 100%;
            height: 800px;
        }

        #phead {
            list-style: none;
            overflow: hidden;
            margin: 0;
            padding: 0;
            border-bottom: 1px solid #ddd;
            margin-bottom: 10px;
        }

        #phead li {
            padding-left: 15px;
            padding-right: 15px;
            float: left;
            cursor: pointer;
            font-size: 13px;
            /*margin-bottom: -1px;*/
            padding-bottom: 10px;
        }

        #phead li.active {
            border-bottom: 2px solid deepskyblue;
            color: deepskyblue;;
        }

        .__tab {
            display: none;
        }

        body{
        }


    </style>

    <link rel="stylesheet" href="jquery.webui-popover.min.css">
    <script src="jquery.webui-popover.min.js"></script>
    <script src="right_menu.js"></script>
    <script src="../../../static/vendor/artTemplate/template-web.js"></script>
    <script>
        window.type = getParam("type");
        window.id = getParam("id");
        window.uid = getParam("uid");

    </script>
    <script src="../lib/bpm/bpmn-viewer.js"></script>
    <script src="../lib/layer/layer.js"></script>
    <script src="../lib/laydate/laydate.js"></script>
    <link rel="stylesheet" href="../lib/web-uploader/webuploader.css">
    <script src="../lib/web-uploader/webuploader.min.js"></script>
    <script src="../lib/vue/vue.js"></script>
    <script>
        $.ajaxSetup({
            headers:{
                "HZToken": getToken()
            },
            crossDomain: true,
            cache: false
        });

        function getToken() {
            if(typeof android != "undefined"){
                return android.jsGetToken()
            } else {
                return "main|0eb217ab-a093-413e-a82e-4a57c6971e7d";
                return "main|f066eb20-09e4-4bd5-91a8-df9200c7699e";
            }
        }
    </script>
</head>
<body>
<div id="panel" style="padding: 10px;">
    <!--<ul id="phead">-->
        <!--<li class="active">表单</li>-->
        <!--<li>流程图</li>-->
        <!--<li class="process">流程日志</li>-->
    <!--</ul>-->
    <div id="pbody">
        <div id="form" class="__tab" style="width: 740px; margin: 0 auto;">

            <script>
                window.Data = null;
                window.FormBody = null;
                // window.FormHtml = "";

            </script>
            <div id="form-content">
            </div>

            <div id="file-app">
                <div style="padding-bottom: 20px;" v-if="files.length">
                    <div v-for="(v,i) in files" v-if="v.action != 'delete' || (v.resp && v.resp.action != 'delete')">
                        {{v.name}}
                        &nbsp;
                        &nbsp;
                        {{v.state}}
                        {{v.percent}}
                        <a href="javascript:;" @click="remove(i)" v-if="!v.creator || v.creator == uid">删除</a>
                        <a :href="'/api/bpm/workflow/download?name=' + (v.name || v.resp.name) + '&path=' + (v.id || v.resp.id)" v-if="!v.uploading || v.state == '成功'">下载</a>
                    </div>
                </div>
            </div>

            <div class="action" style="display: none;text-align: center;">
                <label class="btn btn-warning btn-sm" style="position:relative;overflow: hidden" id="upload">
                    <div id="picker" style="width: 1px;height: 1px;position:absolute;left: -100px;top: -100px;">
                    </div>
                    上传
                </label>
                <a class="btn btn-danger btn-sm" href="javascript:;" id="goBack">回退</a>
                <a class="btn btn-primary btn-sm" href="javascript:;" id="save">保存</a>
                <a class="btn btn-primary btn-sm" href="javascript:;" id="submit">提交</a>
            </div>
        </div>

    </div>
</div>

<DIV class=contextMenu id=myMenu1 style="display: none;">
    <UL>
        <LI id=open style="font-size: 12px;line-height: 20px;vertical-align: middle;"><IMG width="20px" height="20px" style="margin-top: -3px;margin-right: 5px;" src="his.png">提交历史</LI>
    </UL>
</DIV>


</body>
</html>
<script>

    $("#pbody > .__tab").show();


    function loadForm() {
        if(Data != null){
            var body = FormBody = $("#form-content")//$(iframe).contents().find("body");
            body.html(Data.form);
            //全部设为disabled
            // body.find("input[leipiplugins]:not([type=radio]):not([type=checkbox]), textarea[leipiplugins]").val("").prop("disabled", "disabled");
            //只有宏字段和日期被设置为空, 其余需要保留默认值
            body.find("input[leipiplugins=macros], input[leipiplugins=datetime]").val("");
            //设为disabled
            body.find("input[leipiplugins], textarea[leipiplugins], select[leipiplugins]").prop("disabled", "disabled");
            //select默认选第一个
            // body.find("select[leipiplugins]").each(function () {
            //     $(this).val($(this).find("option:first").val())
            // })

            //编辑模式
            // if(type == 'edit'){
            //     Data.formFields = [];
            //     for(var i in Data.allFields){
            //         Data.formFields.push(i)
            //     }
            // }

            //当前节点可编辑
            // $.each(Data.formFields || [], function (i, v) {
            //     if(!Data.allFields[v]){
            //         return
            //     }
            //     var elem = body.find("[name=" + Data.allFields[v].name + "]");
            //     // elem.removeProp("disabled").css("border", "1px solid blue")
            //     if(elem.is("[leipiplugins=datetime]")){
            //         elem.prop("readonly","true")
            //
            //         ;(function (title, type) {
            //                 laydate.render({
            //                     elem: "[leipiplugins=datetime][title="+title+"]"
            //                     ,type: (function () {
            //                         switch (type) {
            //                             case "日期" :
            //                                 return "date";
            //
            //                             case "日期+时间":
            //                                 return "datetime";
            //
            //                             case "时间":
            //                                 return "time";
            //                         }
            //                     })()
            //             })
            //         })(elem[0].title, elem.attr("orgformat"));
            //     }
            //
            //     if(elem.is("[leipiplugins=sign]")){
            //         elem.click(function () {
            //             var id = $(this).attr("name");
            //             var src = $(this).attr("src");
            //             window.open("./sign.html?name=" + id + "&src=" + src, "bpm-sign", "left=100, top=100, width=500, height=500, location=no")
            //         });
            //     }
            // });

            //必填字段标红
            // $.each(Data.requiredFields || [], function (i, v) {
            //     body.find("[name=" + Data.allFields[v].name + "]").removeProp("disabled").css("border-color", "red")
            // });

            //时间字段

            //字段赋值
            $.each(Data.attrs, function (i, v) {
                var field = Data.allFields[i];
                if (!field) return
                var t = body.find("[name=" + field.name + "]")
                if (field.leipiplugins == 'macros') {
                    t.prop("readonly", "true")
                }

                if(t.is("[leipiplugins=sign]")){
                    var matched = v.match(/^\[img\](.+)$/);
                    if(matched){
                        t.attr('src', matched[1])
                    }
                } else {
                    t.val(v)
                }
            });

            //必填字段标红
        }

    };

    // 子页面调用函数
    function getData() {
        var data = {};
        $.each(Data.formFields || [], function (i, v) {
            var key = v;
            if(!Data.allFields[v]){
                return
            }
            var elem = FormBody.find("[name=" + Data.allFields[v].name + "]");
            var val;
            if(elem.is("[leipiplugins=sign]")){
                val = elem.attr("src");
                if(val.indexOf("sign.png") > -1){
                    val = "";
                } else {
                    val = "[img]" + val;
                }
            } else {
                val = elem.val();
            }
            data[key] = val;
        });

        //提交所有这个节点上的文件
        var _files = files.files
            .filter(function (e) {
                return !e.uploading;
            })
            .filter(function (e) {
                return e.resp || e.action == "delete";
            })
            .map(function (e) {
                return e.resp ? e.resp : e;
            });
        return ({
            data: data,
            files: _files
        })
    }


    function load() {
        // $(".action").hide();
        $("#upload").hide();
        $("#goBack").hide();
        $(".process").hide();


        // console.log(type,id)
        // var id = getParam("id");
        var layerIndex = layer.load(0, {
            time: 5000
        });

        if(type == 'pub'){
            document.title = "发布任务";
        } else {
            document.title = "处理任务";
        }

        var ajax = null;
        if(window.type == 'pub'){
            ajax =  $.get("/api/bpm/workflow/preparePub", {id: window.id});
        } else {
            ajax = $.get("/api/bpm/workflow/getInsInfo", {id: window.id});
            // loadLogs(window.id);
        }

        $.when(ajax).then(function (msg) {
            layer.close(layerIndex);
            if (!msg.success) {
                layer.msg(msg.errMessage)
                return;
            }

            Data = msg.data;

            if(msg.data.files && msg.data.files.length){
                files.files = msg.data.files
            }
            // FormHtml = msg.data.form;
            loadForm()
            // $("#iframe").attr("src", "./form.html?v=" + Math.random())


            //事件
            if(type == 'pub'){
                // $(".action").show();
            } else if((type == 'deal' && msg.data.deal) || (type == 'edit')){
                // $(".action").show();
                if(type == 'edit'){
                    $(".action #submit").hide();
                }
            } else {
                if(type == 'deal'){
                    document.title = "查看任务";
                }
            }

            // if(msg.data.allowBack){
            //     $("#goBack").show();
            // }
            //
            // if(msg.data.node && msg.data.node.allowUpload){
            //     $("#upload").show();
            // }
            //
            // if(type != "pub"){
            //     $(".process").show()
            // }
        }, "json");
    }


    //加载页面
    load();

    $("#save").click(function () {
        submit(false);
    });

    $("#submit").click(function () {
        // getData();
        submit(true);
    });

    // $("#goBack").click(function () {
    //     layer.confirm('确定回退？', function(index){
    //         //do something
    //         layer.close(index);
    //         $.get("/api/bpm/workflow/goBack", {id: id}, function (msg) {
    //             if(!msg.success){
    //                 return layer.msg(msg.errMessage)
    //             }
    //             layer.msg("回退成功")
    //             load();
    //         },"json");
    //     });
    // });


    ;(function () {
        //初始化webuploader
        var uploader = WebUploader.create({
            // swf文件路径
            swf: '../lib/web-uploader/Uploader.swf',
            // 文件接收服务端。
            server: '/api/bpm/workflow/upload',
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#picker',
            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            resize: false,
            auto: true,
            duplicate: true,
            fileVal: "file"
        }).on("uploadStart", function (file) {
            file.percent = "0%";
            file.state = '上传中';
            file.uploading = true;
            files.files.push(file);
            // console.log(file)
        }).on("uploadProgress", function (file,percentage ) {
            file.percent = (percentage * 100).toFixed(0) + "%";
        }).on("uploadSuccess", function (file,response) {
            if(response.success){
                file.state = "成功";
                file.uploading = false;
                file.resp = response.data;
            } else {
                file.state = "失败";
            }
        }).on("uploadError", function (file) {
            file.state = "失败";
        }).on("uploadComplete", function (file) {
            file.percent = "";
        });
    })();

    var files = new Vue({
        el: "#file-app",
        data:{
            files: [],
            uid: uid
        },
        methods: {
            remove: function (i) {
                var item = this.files[i];
                //上传中直接再见
                if(item.uploading){
                    this.files.splice(i);
                    return
                }
                if(item.resp){
                    item.resp.action = "delete";
                } else {
                    item.action = "delete";
                }
            }
        }
    })
</script>


